var S_MAIL_FROM = "mailfrom";
var S_MAIL_TO = "mailto";
var EAMIL_ID = "emailId";

var EMALIS = [];
var BRS = new Array("PDF_file_for_each_XML_file","XML_validation"); 

var actionhandlers_doc;

 
function init_callback( model ){

   var actionclass = model.getAction().actionClass;
   if(actionclass == "com.reallysi.service.workflow.action.MailSendHandler"){
       var objs = model.getAction().variables;
       removeAllVarible(variables);
       for (i=0; i<objs.length; i++){
	      addVariable(objs[i][0],objs[i][1]);
       }
   }
}

function initialzePage(model){
	//initialize action handlers
	/*
	if(actionhandlers_doc == null){
		//construct default values
		var dValues = new Array(model.getAction().actionClass, model.getExceptionhandler().actionClass);
		GetActionHandlerList( Init_actionhandler_select, dValues );
	}
	
   //general
   //check the EMALIS array, fill it in with values when only the array object is empty
   if(EMALIS.length<=0){
       new Ajax( GetAllUsers(), _GetAllEmails_Handler, new Array(init_callback, model));
   }*/
   document.all.general_name.value = model.getText();
   //document.title=model.getText();
   //action
   document.all.variables_action.value = model.getAction().actionClass;
   document.all.exceptionvariables_action.value = model.getExceptionhandler().actionClass;
   var objs = model.getAction().variables;
   removeAllVarible(variables);
   removeAllVarible(exceptionvariables);
   for (i=0; i<objs.length; i++){
	  addVariable(objs[i][0],objs[i][1]);
   }

   var objs = model.getExceptionhandler().variables;
   for (i=0; i<objs.length; i++){
	  addVariable(objs[i][0],objs[i][1], exceptionvariables);
   }
   
   //to revise some object printed
   //alert( $( EAMIL_ID ) );
	//if( $( EAMIL_ID ) ) new Ajax( GetAllUsers(), _GetAllEmails_Handler);

}

function initialzeDecisionPage(model){
    //alert(model.getText());
	document.all.Name_.value = model.getText();
	document.all.ConditionExpression.value = model.getCondition().conditionExpression;
	changeDecisionTag('condition');
}

function initialzeForkPage(model){
  document.all.forknode_name.value = model.getText();
}

function initialzeJoinPage(model){
  document.all.joinnode_name.value = model.getText();
}

  function _Pick_Item( s, item )
  {
  	var start = s.indexOf( item )+item.length;
  	s = s.substring( start );
  	return s.substring( 0, s.indexOf( "," ) );
  }
function initVariables(el, table){

   removeAllVarible(table);
   var variabaleNode = actionhandlers_doc.selectSingleNode("//RSUITE:PROCESS-ACTION-HANDLER-DEF/RSUITE:PROCESS-ACTION-HANDLER[RSUITE:CLASS='"+el.value+"']/RSUITE:VARIABLES");
   if( variabaleNode!=null ){
     var variables = variabaleNode.childNodes;
     var type = variabaleNode.selectSingleNode("../RSUITE:TYPE");
     
     //alert(variables.length);
     //alert(type.text);
     for(var i =0;i<variables.length; i++){
   	   var variable = variables[i];
   	   //alert(variable.text);
   	   if( type.text =="normal" ){
   	   	  addVariable(variable.text);
   	   }else if(type.text =="exception"){
   	   	  addVariable(variable.text, null, exceptionvariables);
   	   }
   	   
     }
   }
   
   
   /*   
   switch(el.value){
       case "com.reallysi.service.workflow.action.MailSendHandler":
           addVariable(S_MAIL_TO);
           addVariable(S_MAIL_FROM);
           addVariable("subject");
           addVariable("content");
           addVariable("attachments");
           break;
       case "com.reallysi.service.workflow.action.InvokeRQLHandler":
           addVariable("rql");
           break;   
       case "com.reallysi.service.workflow.action.BatchLoadActionHandler":
           break;  
       case "com.reallysi.service.workflow.action.ExportActionHandler":
           break;
       case "com.reallysi.service.workflow.action.InvokeXQYModule":
           addVariable("module_name");
           addVariable("function_name");
           break;
       case "com.reallysi.service.workflow.action.InvokeExternalCommand":
       	   addVariable("program_name");
           break;   
       case "com.reallysi.service.workflow.action.XMLTransform":
           addVariable("Input_folder");
           addVariable("output_folder");
           addVariable("xslt_path");
           break;   
	   case "com.reallysi.service.workflow.action.ExceptionHandlerGoTo":
           addVariable("transitionName", null ,exceptionvariables);
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.UnzipActionHandler":
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.LoadActionHandler":
	       addVariable("regex");
		   addVariable("xpathListByComma");
		   addVariable("xpathForLA");
		   addVariable("xpathAbstract");
		   addVariable("collection");
    	   break;
	   case "com.reallysi.service.workflow.ingestion.action.AddLayeredMetadataActionHandler":
		   addVariable("metadataName");
		   addVariable("metadataValue");
    	   break;    	
    	    
	   case "com.reallysi.service.workflow.ingestion.action.AddContentAssemblyActionHandler":
		   addVariable("importRuleName");
    	   break;    	         	   
	   case "com.reallysi.service.workflow.ingestion.action.RQLActionHandler":
		   addVariable("rql");
    	   break; 
       case "com.reallysi.service.workflow.ingestion.action.CreateFolderActionHandler":
	       addVariable("folder");
	       break;
       case "com.reallysi.service.workflow.ingestion.action.CreateCAActionHandler":
	       addVariable("ca");
	       addVariable("parentUri");
	       break;
       case "com.reallysi.service.workflow.ingestion.action.CreateCANodeActionHandler":
	       addVariable("canode");
	       addVariable("ca");
	       addVariable("folder");
	       break;
       case "com.reallysi.service.workflow.ingestion.action.AddXML2CAActionHandler":
   		   break;
       case "com.reallysi.service.workflow.ingestion.action.FileParseActionHandler":
	       addVariable("regex");
	       addVariable("parameters");
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.ReadablePDFCheckActionHandler":
	       addVariable("failDetail");
	       
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.XMLFieldEqualCheckActionHandler":
	       addVariable("xpaths");
	       addVariable("values");
	       addVariable("operation");
	       addVariable("failDetail");
	       
	       break; 
	   case "com.reallysi.service.workflow.ingestion.action.VariableMatchAction":
	       addVariable("variable1");
	       addVariable("variable2");
	       addVariable("failDetail");
	       
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.PostCheckActionHandler":
	       addVariable("functionName");
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.FileNamePatternMatchActionHandler":
	       addVariable("regex");
	       addVariable("failDetail");
	       
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.VariableAssignActionHandler":
	       addVariable("source");
	       addVariable("target");
	       break;
	       
	//   case "com.reallysi.service.workflow.delivery.action.AssignVariableActionHandler":
	//       addVariable("name");
	//       addVariable("value");
	//       break;
	       
	   case "com.reallysi.service.workflow.ingestion.action.CheckPDFForEachXMLActionHandler":
	       addVariable("failDetail");
	       
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.ValidateAgainstDtdSchemaActionHandler":
	       addVariable("publicId");
	       addVariable("dtdSchemaName");
	       addVariable("failDetail");
	       
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.BatchUpdateActionHandler":
	       addVariable("rql");
	       addVariable("revisionType");
	       addVariable("revisionNote");
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.BackupRSuiteActionHandler":
	       addVariable("directory");
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.RestoreRSuiteActionHandler":
	       addVariable("directory");
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.ExtractFileFromZipAction":
	       addVariable("regex");
	       break;
	   case "com.reallysi.service.workflow.delivery.action.ReadInputVariableActionHandler":
	       break;
	   case "com.reallysi.service.workflow.delivery.action.GetContentActionHandler":
		   addVariable("queryType");
	       addVariable("query");
	       addVariable("breadth");
	       break;
	   case "com.reallysi.service.workflow.delivery.action.InvocationOfSubWorkflowsHandler":
	       addVariable("workFlowName");
	       addVariable("names");
	       addVariable("values");
	       break;
	   case "com.reallysi.service.workflow.delivery.action.NotificationActionHandler":
	       break;
	   case "com.reallysi.service.workflow.delivery.action.PDFEnhancerActionHandler":
	       addVariable("configureFile");
	       addVariable("configureFileType");
	       addVariable("sourceFile");
	       addVariable("destFileFolder");
	       break;
	   case "com.reallysi.service.workflow.delivery.action.XQueryMergeActionHandler":
	       addVariable("functionName");
	       addVariable("parameters");
	       break;
	   case "com.reallysi.service.workflow.delivery.action.XSLTransformActionHandler":
	       addVariable("xslFile");
	       break;
	   case "com.reallysi.service.workflow.delivery.action.ExportActionHandler":
	   	   addVariable("packageURI");
		   addVariable("targetURI");
		   addVariable("interval");
		   addVariable("retryAtt");
		   addVariable("username");
		   addVariable("password");
	       break;
	   case "com.reallysi.service.workflow.ingestion.action.AddFile2ZipAction":
	   	   addVariable("regex");
		   addVariable("zipFileName");
		   break;
	   case "com.reallysi.service.workflow.action.ExportObjectsActionHandler":
	   	   addVariable("objectIds");
		   addVariable("destinationPath");
	       break;
   }*/
}
	function changeTag(_tagId){
		var tagShowed = document.getElementById(_tagId);
		if(tagShowed){
			//var tags = document.getElementsByTagName("DIV");
			
			var tags1 = document.getElementById("general");
			var tags2 = document.getElementById("handler");
			var tags3 = document.getElementById("exceptionhandler");
			var tags= new Array(tags1,tags2,tags3);
			for(var i=0;i<tags.length;i++){
				var aTag = tags[i];
				
					if(aTag.id==_tagId || aTag.id==""){
						aTag.style.display = "block";
					}else{
						aTag.style.display = "none";
					}
			}
		}
	}
 
  function send(){     
 
      //  propertiesNodeDialog.titleInput.value=document.all.general_name.value;
      //  propertiesNodeDialog.model.setAction(getAction(variables.id));
		//propertiesNodeDialog.model.setExceptionhandler(getAction(exceptionvariables.id));
			
		propertiesNodeDialog.titleInput.value = document.all.general_name.value;
        propertiesNodeDialog.model.setAction(getAction(variables.id));
		propertiesNodeDialog.model.setExceptionhandler(getAction(exceptionvariables.id));
		propertiesNodeDialog.model.setText(propertiesNodeDialog.titleInput.value);
		propertiesNodeDialog.titleInput.style.display = "none";
		propertiesNodeDialog.titleTxtCell.style.display = "";
		propertiesNodeDialog.titleInputCell.style.display = "none";
        propertiesNodeDialog.model.setEditing(false);
	 
		propertiesNodeDialog.hide();
    }
    
    function Action(){
    this.actionClass = "";
	this.variables = new Array();
}
function addVariable(name, value, table){
  var el_table = variables;
  if(table) el_table = table;
  var row = el_table.insertRow(-1);

  var cell_name = row.insertCell(-1);
  var cell_value = row.insertCell(-1);
  var cell_chk =  row.insertCell(-1);

  var ipt_name_name = el_table.id + "_names";
  var ipt_value_name = el_table.id + "_vars";
  var ipt_name;
  if(window.ActiveXObject){
	  ipt_name = document.createElement("<input type=\"text\" name=\""+ipt_name_name+"\">");
  } else {
  		ipt_name = document.createElement("input");
  		ipt_name.type = "text";
  		ipt_name.name = ipt_name_name;
  }
  
  //var ipt_value = document.createElement("<input type=\"text\" name=\"vars\">");
  var ipt_value;
//  if( name == S_MAIL_FROM || name == S_MAIL_TO )
//  {
//  	ipt_value = document.createElement("<select id=\""+EAMIL_ID+"\" name=\""+ipt_value_name+"\"><option value='1'>1</option></select>");
//  	for( var i = 0; i<EMALIS.length; i++ )
//  	{
//  		var sperateIndex = EMALIS[i].indexOf( "," );
//  		var oOption = document.createElement("OPTION");
//		with( oOption ){ text=EMALIS[i].substring(0,sperateIndex); value=EMALIS[i].substring(sperateIndex+1);}
//  		ipt_value.add( oOption );
//  	}
//  }
//  else 
  if ( name == "transitionName" )
  {
  	   if(window.ActiveXObject){
	       ipt_value = document.createElement("<select name=\""+ipt_value_name+"\"><option value='1'>1</option></select>");
  	   } else {
  	   	   ipt_value = document.createElement("select");
	       ipt_value.name = ipt_value_name;
	       ipt_value_op = document.createElement("option");
	       ipt_value_op.value = "1";
	       ipt_value.add(ipt_value_op);
  	   }
	   var model =  propertiesNodeDialog.model;
	   var transitionModels = model.getFroms();
	    for (var i = 0; i < transitionModels.size(); i++) {
            var transitionModel = transitionModels.get(i);
		    var oOption = document.createElement("OPTION");
		    with( oOption ){ text=transitionModel.getText(); value=transitionModel.getText();}
  		    ipt_value.add( oOption );
		}
  }else if (name=="brNames"){
		 if(window.ActiveXObject){
		   ipt_value = document.createElement("<select name=\""+ipt_value_name+"\" size=\""+BRS.length+"\" multiple=\"multiple\"></select>");
		 } else {
		   ipt_value = document.createElement("select");
		   ipt_value.name = ipt_value_name ;
		   ipt_value.multiple = "multiple";
		   ipt_value.size = BRS.length;
		 }
	   
	 for( var i = 0; i<BRS.length; i++ )
  	{
  		
  		var oOption = document.createElement("OPTION");
		with( oOption ){ 
		text=BRS[i]; 
		value=BRS[i];
		}
  		ipt_value.add( oOption );
  	}

  }
  else
    var ipt_chk ;
    if(window.ActiveXObject){
	   	ipt_value = document.createElement("<input type=\"text\" name=\""+ipt_value_name+"\">");
	    ipt_chk = document.createElement("<input type=\"checkbox\" name=\"chk\">");
    } else {
    	ipt_value = document.createElement("input");
		ipt_value.type = "text";
		ipt_value.name = ipt_value_name;
		
		ipt_chk = document.createElement("input");
		ipt_chk.type = "checkbox";
		ipt_chk.name = "chk";
		ipt_chk.id = "chk";
    }

// edit .init the value 
  if(name) ipt_name.value = name;
  if(value){

        if(ipt_value.type=="select-multiple"){
            var arrValue = value.split(";");
            for(var i = 0;i<arrValue.length;i++){
                for(var j = 0 ;j < ipt_value.options.length; j++){
                    if(ipt_value.options[j].text==arrValue[i]) ipt_value.options[j].selected=true;
                }
             }
        }else{
			if(value.isList){
			    ipt_value.value = value[0];
                ipt_value.values = value;
			}else{
                ipt_value.value = value;
			}
        }

  };

  // add value list button
  var ipt_btn;
  if(window.ActiveXObject){
	  ipt_btn = document.createElement("<input type=\"button\" name=\"addvaluebtn\" onclick=\"addValueList(this)\" value=\"+\" alt=\"Add new value.\">");
  } else {
      ipt_btn = document.createElement("input");
  	  ipt_btn.name = "addvaluebtn";
	  ipt_btn.type = "button";
	  //ipt_btn.onclick = "addValueList(this)";
	  var lengthElm = document.getElementsByName('addvaluebtn').length;
	  ipt_btn.onclick = function(){
		  var index = lengthElm;
		  var node = document.getElementsByName('addvaluebtn')[index]
		  addValueList(node)
	  };
	 } 
  ipt_btn.value = "+";
  ipt_btn.alt = "Add new value.";
  
  ipt_btn.targetObj = ipt_value;
  ipt_btn.targetName = ipt_name.value;
  
  cell_name.appendChild(ipt_name);
  cell_value.appendChild(ipt_value);
  cell_chk.appendChild(ipt_chk);

  cell_chk.appendChild(ipt_btn);
}

//set node action handler values
function addValueList(me){
  //alert(me.value);
  //alert(me.targetObj.value);
  //alert(me.targetObj.values);
  //initialize value list
  clearNodeValues();
  $("valuelisttitle").innerHTML =  "<font color=black>"+ $("valuelisttitle").innerHTML +  "</font><font color=red><br>"+me.targetName + "</font>";//set title

  //set values
  if(!me.targetObj.values){
	  var a = new Array();
	  me.targetObj.values = a;
  }
  me.targetObj.values[0] = me.targetObj.value;
  for(var i=1;i<me.targetObj.values.length;i++){
    addNodeValue(me.targetObj.values[i]);
  }
  //add a new value
  addNodeValue();

  nodeValuesDialog.targetObj = me.targetObj;

  nodeValuesDialog.show();
}

function setNodeValues(){
   var objs_values=document.getElementsByName("nodevaluelist_value");
   var a = new Array();
   if(nodeValuesDialog.targetObj.value) a[0] = nodeValuesDialog.targetObj.value;
   for(i=0;i<objs_values.length;i++){
      if(objs_values[i].value !=""){	
		a[i+1] = objs_values[i].value;
	  }
   }
   
   nodeValuesDialog.targetObj.values = a;
   nodeValuesDialog.hide();
}

function clearNodeValues(){
   $("valuelisttitle").innerHTML = "Add a new value to the variable: ";
   for(var i=0;i<$("nodeValueList").rows.length;i++){
     $("nodeValueList").deleteRow(i);
     i--;
   }
}

function addNodeValue(value){ 
   var values_table = $("nodeValueList");
   var row = values_table.insertRow(-1);
   var cell = row.insertCell(-1);
   var ipt_newvalue;
   if(window.ActiveXObject){
	   ipt_newvalue = document.createElement("<input type=\"text\" size=40 name=\"nodevaluelist_value\">");
   } else {
	   ipt_newvalue = document.createElement("input");
	   ipt_newvalue.type = "text";
	   ipt_newvalue.size = 40;
	   ipt_newvalue.name = "nodevaluelist_value";
   }
   
   
   if(value){
     ipt_newvalue.value = value;
   }
   cell.appendChild(ipt_newvalue);
}
//remove variables
/*
function removeVarible(){
   var objs=document.getElementsByName("chk");
   var index=0;
   for(i=0;i<objs.length;i++){
     if(objs[i].checked){
        index=objs[i].parentElement.parentElement.rowIndex;
        variables.deleteRow(index);
        i--;
     }
   }
}*/
//remove variables by a specific table
function removeVarible(table){
   if(!table) table = variables;
   var objs=document.getElementsByName("chk");
   var index=0;
   for(i=0;i<objs.length;i++){
	   if(window.ActiveXObject){
		   	if(objs[i].checked){
		        index=objs[i].parentElement.parentElement.rowIndex;
		        table.deleteRow(index);
		        i--;
		     }
	   }
	   else {
		   if(objs[i].checked == true){
		        index=objs[i].parentNode.parentNode.rowIndex;
		        table.deleteRow(index);
		        i--;
		     }
	   }
   }
}
//remove all variables
function removeAllVarible(table){
   for(var i=1;i<table.rows.length;i++){
     table.deleteRow(i);
     i--;
   }
}
 function _GetAllEmails_Handler( xmlhttp, func, para )
  {
  	//alert( xmlhttp.responseXML.xml );
	var xmlResponse = xmlhttp.responseXML;

	if( xmlResponse.xml.indexOf( "RsException" ) > 0 )
	{
		alert("something wrong when fetch all user email from ladap server!.");
		return;
	}
	
	try{
		//alert( xmlResponse.selectNodes("/RESULT/ELEMENT").length );
		/*
		var emails = $A( xmlResponse.selectNodes("/RESULT/ELEMENT") ).each( function( value, index ){
			//alert( "push: "+ _Pick_Item( value.text, "fullname=" )+","+ _Pick_Item( value.text, "email=" ) );
			EMALIS.push( _Pick_Item( value.text, "fullname=" )+","+ _Pick_Item( value.text, "email=" ) );
		});*/
		
		var emails = xmlResponse.getElementsByTagName("ELEMENT");
		for(var i=0; i<emails.length; i++){
			EMALIS.push( _Pick_Item( emails[i].firstChild.nodeValue, "fullname=" )+","+ _Pick_Item( emails[i].firstChild.nodeValue, "email=" ) );
		}
	}catch(e){
	   alert(e.message);
	}
    //invoke callback handler
	func(para);
  }
function _Pick_Item( s, item )
  {
  	var start = s.indexOf( item )+item.length;
  	s = s.substring( start );
  	return s.substring( 0, s.indexOf( "," ) );
  }
function getAction(tableid){
   var objs_name=document.getElementsByName(tableid+"_names");
   var objs_value=document.getElementsByName(tableid+"_vars");

   var action = new Action();
   action.actionClass = eval("document.all."+tableid+"_action.value");
/*
   for(i=0;i<objs_name.length;i++){
      if(objs_name[i].value !="" && objs_value[i].value!=""){
		var a = new Array();
		a[0] = objs_name[i].value;
		a[1] = objs_value[i].value;
		
		action.variables[action.variables.length] = a;
	  }
   }
*/
    for(i=0;i<objs_name.length;i++){
        if(objs_value[i].type=="select-multiple"){
            if(objs_name[i].value !=""){
                var a = new Array();
                a[0] = objs_name[i].value;
                var value = "";
                //get all the selected option value 
                for(var j=0;j<objs_value[i].options.length;j++){ 
		            if(objs_value[i].options[j].selected){
			             if(value==""){			
			 	            value=objs_value[i].options[j].text; 
			             }else{
			 	            value=value+";"+objs_value[i].options[j].text;
			             };
			         };    
		         };
		         
		         a[1] = value;
		         //add a new item to the Array action.variables
		         action.variables[action.variables.length] = a;
            		
            }
        }else{
           if(objs_name[i].value !=""){
		        var a = new Array();
		        a[0] = objs_name[i].value;
		        a[1] = objs_value[i].value;
               

				if(objs_value[i].values){
					if(objs_value[i].values.length>1){
				        objs_value[i].values.isList = true;
                        objs_value[i].values[0] = objs_value[i].value;
                        a[1] = objs_value[i].values;
					}else{
					    objs_value[i].values.isList = false;
					}
				}

        					
		        action.variables[action.variables.length] = a;
	       }          
        }
    }   
   return action;
}
 
function initialzeTaskPage(model){
   
   //var comboBox = new ComboBox(controller);
    removeAllTaskVarible();
   
   var text = model.getText();
   var taskName = model.taskName;
   var description = model.description;
   var duedate = model.duedate;
   if(text == null) text = "";
   if(taskName == null) taskName = "";
   if(description == null) description = "";
   if(duedate == null) duedate = "";
   document.all.Name.value = text;
   document.all.Taskname.value = taskName;
   document.all.Description.value = description;
   document.all.Duedate.value = duedate;
   
   if(model.getTask().assignment.actorId != null && model.getTask().assignment.actorId != ""){actors_label.innerText = "Actor_id";actors.value = model.getTask().assignment.actorId}
   if(model.getTask().assignment.pooledActors != null && model.getTask().assignment.pooledActors !=""){actors_label.innerText = "组别";actors.value = model.getTask().assignment.pooledActors}
   //alert(model.getTask());

   var objs = model.getTask().controller.variables;

   //get access properties
   var a = new Array();
   if(objs[0] && !objs[0][1]){
       for (var i=0; i<objs.length; i++){
	      if(objs[i][4] == null){
	      	objs[i][4] = "read,write";
	      }
	      a = objs[i][4].split(",");
          for(var j=0;j<a.length;j++){
              if(a[j]) objs[i][j+1] = true;
              else objs[i][j+1] =false;
          }
       }      
   }

   for (i=0; i<objs.length; i++){
	  addTaskVariable(objs[i][0], objs[i][1], objs[i][2], objs[i][3]);
   }
   //initialize event
   var events = model.getTask().event;
   $("Enter_Actionname").value = events.actionname_enter;
   $("Enter_Actionclass").value = events.actionclass_enter;
   $("Enter_Mapping").value = events.mapping_enter;
   $("Leave_Actionname").value = events.actionname_leave;
   $("Leave_Actionclass").value = events.actionclass_leave;
   $("Leave_Mapping").value = events.mapping_leave;

   //$("Taskcreate").value = events.create;
   //$("Taskassign").value = events.assign;
   //$("Taskstart").value = events.start;
   //$("Taskend").value = events.end;
   //initialize assignment properties
   //initialize user select options
   //if(users.options.length<=1){
	//   getAllUsers();
   //}
							
    //initialize group select options
	//if(groups.options.length<=1){
	//	getAllGroups();
	//}
	//$("users").value = "";$("users").disabled = false;
	//$("groups").value = "";$("groups").disabled = false;
	
	changeTaskTag('taskname');
}
function _GetTaskAllUsers_Handler(xmlhttp){ _Node2Option( xmlhttp, "users" ); }
function _GetTaskAllGroups_Handler(xmlhttp){ _Node2Option( xmlhttp, "groups" ); }

function changeTaskTag(_tagId){
		var tagShowed = document.getElementById(_tagId);
	 
		if(tagShowed){
				var tags1 = document.getElementById("taskname");
			var tags2 = document.getElementById("event");
			var tags3 = document.getElementById("controller");
			var tags4 = document.getElementById("assignment");	
			var tags= new Array(tags1,tags2,tags3,tags4);
			for(var i=0;i<tags.length;i++){
				var aTag = tags[i];
					if(aTag.id==_tagId){
						aTag.style.display = "block";
					}else{
						aTag.style.display = "none";
					}
			}
		}

		
	}

function changeDecisionTag(_tagId){
	var tagShowed = document.getElementById(_tagId);
	if(tagShowed){
		var tags1 = document.getElementById("condition");	
		var tags= new Array(tags1);
		for(var i=0;i<tags.length;i++){
			var aTag = tags[i];
			if(aTag.id==_tagId){
				aTag.style.display = "block";
			}else{
				aTag.style.display = "none";
			}
		}
	}
}

function changeProcessTag(_tagId){
	var tagShowed = document.getElementById(_tagId);
	if(tagShowed){
		var tags1 = document.getElementById("processgeneral");	
		var tags2 = document.getElementById("processevent");
		var tags= new Array(tags1,tags2);
		for(var i=0;i<tags.length;i++){
			var aTag = tags[i];
			if(aTag.id==_tagId){
				aTag.style.display = "block";
			}else{
				aTag.style.display = "none";
			}
		}
	}
}

	function _Node2Option( xmlhttp, destId ){
	//alert( xmlhttp.responseXML.xml );
	var xmlResponse = xmlhttp.responseXML;

	if( xmlResponse.xml.indexOf( "RsException" ) > 0 )
	{
		alert("something wrong when fetch all "+destId+" from ladap server!.");
		return;
	}
	
	try{
 /*
		var actors=$("actors").value;
		$(destId).innerHTML="";
	if(destId=="groups"){
			 var oOption = document.createElement("OPTION");
			 oOption.text = "Please choose a group";
			 oOption.value = "";	  
			 $(destId).add(oOption);						 
	}else{
			 var oOption = document.createElement("OPTION");
			 oOption.text = "Please choose an user";
			 oOption.value = "";	  
			 $(destId).add(oOption);	
		  }    */
		var elements = xmlResponse.getElementsByTagName("ELEMENT");
		for(var i=0;i<elements.length;i++){
			var value_text = elements[i].firstChild.nodeValue;
			var user = _Pick_String(value_text);
			var oOption = document.createElement("OPTION");
			oOption.text = user;
			oOption.value = value_text;	     
			           		  
		 
		 	$(destId).add(oOption);			
		}
 
	}catch(e){
	   alert(e.message);
	}
}
function _Pick_String( s ) {
  // Sometimes the names are "bare" and sometimes the names are LDAP Distinguished names
  if (s.indexOf("=") == -1)
    return s;
  return   s.substring( s.indexOf( "=" ) +1, s.indexOf( "," ) );
}

function getCondition(){
	var condition = new Condition();
	condition.conditionExpression = document.all.ConditionExpression.value;
	return condition;
}

function getTask(){
   var objs_name=document.getElementsByName("names");
   var objs_read=document.getElementsByName("read");
   var objs_write=document.getElementsByName("write");
   var objs_required=document.getElementsByName("required");

   var accessStr="";

   var task = new Task();
   task.taskName = document.all.Taskname.value;
   task.description = document.all.Description.value;
   task.duedate = document.all.Duedate.value;
   
   if(actors_label.innerText == "组别") task.assignment.pooledActors = actors.value;
   if(actors_label.innerText == "用户") task.assignment.actorId = actors.value;

   for(i=0;i<objs_name.length;i++){
      if(objs_name[i].value !=""){
		var a = new Array();
		a[0] = objs_name[i].value;
		a[1] = objs_read[i].checked;
		a[2] = objs_write[i].checked;
		a[3] = objs_required[i].checked;
		accessStr="";
		var acc = new Array();
		if(objs_read[i].checked) acc[acc.length] = "read";//accessStr += "read";accessStr +=",";        
        if(objs_write[i].checked) acc[acc.length] = "write";//accessStr += "write";accessStr +=",";
		if(objs_required[i].checked) acc[acc.length] = "required";//accessStr += "required";
		for(var j=0; j<acc.length; j++){
			accessStr += acc[j];
			if(j+1 < acc.length){
				accessStr += ",";
			}
		}
		if(acc.length == 0){
			accessStr = "read,write";
		}
		a[4] = accessStr;
		task.controller.variables[task.controller.variables.length] = a;
	  }
   }
   //set event
   task.event.actionname_enter = $("Enter_Actionname").value;
   task.event.actionname_leave = $("Leave_Actionname").value;
   task.event.actionclass_enter = $("Enter_Actionclass").value;
   task.event.actionclass_leave = $("Leave_Actionclass").value;
   task.event.mapping_enter = $("Enter_Mapping").value;
   task.event.mapping_leave = $("Leave_Mapping").value;
   return task;
}
function AssignGroup( me ){
    /*if(me.value == ""){
      me.value ="";
      me.users="";
      groups.disabled = false;    
      users.disabled = false;
      return;
    }else{
      if( me.id == "users" ) groups.disabled = true;
      if( me.id == "groups" ) users.disabled = true;
    }
	if( me.id == "users" ){ 
		//ASSIGNER.push = me.options[me.selectedIndex].text; 
		//alert( "you assigned the task to " +  me.options[me.selectedIndex].text ); 
		actors.value = me.options[me.selectedIndex].text;
	}else if( me.id == "groups" ){
		var dn = me.options[me.selectedIndex].value;
		//alert( "dn: " +dn+ "\r\n url: "+ GetUsers( dn ) );
		//new Ajax( GetUsers( dn ), _GetUsers_Handler, new Array(actors));
		//actors_label.innerText = "Actor_id";
		actors.value = me.options[me.selectedIndex].text;
	} */
	if(actors.value){
		actors.value = "";
	}
	actors.value = me.options[me.selectedIndex].text;
}

function AssignUser( me ){
	var value = actors.value;
	if(value){
		var groups = document.getElementById("groups");
		actors.value = groups.options[groups.selectedIndex].text + me.options[me.selectedIndex].text;
	} else {
		alertMessage("请先选择局");
	}
}

function Condition(){
    this.conditionExpression = "";
}

//define task structure   by Ray
function Task(){
    this.taskName = "task1";
	this.description = "";
	this.duedate = "";
	this.controller = new Controller();
	this.assignment = new Assignment();
	this.event = new Event();
}
//define controller structure 
function Controller(){
	this.variables = new Array();
}
//define assignment structure 
function Assignment(){
	this.actorId = "";
	this.pooledActors = "";
	this.groupId = "";
}
//define event structure
function Event(){
	this.actionname_enter = "";
	this.actionname_leave = "";
	this.actionclass_enter = "";
	this.actionclass_leave = "";
	this.mapping_enter = "";
	this.mapping_leave = "";
    this.create = "";
	this.assign = "";
	this.start = "";
	this.end = "";
}
 
//add a variable
function addTaskVariable(name, isRead, isWrite, isRequired){
  var row=variablesTask.insertRow();
  var cell_name = row.insertCell();
  var cell_chk_read = row.insertCell();
  var cell_chk_write = row.insertCell();
  var cell_chk_required = row.insertCell();
  var cell_chk =  row.insertCell();

  //alert(isRead);
  var ipt_name = document.createElement("<input type=\"text\" name=\"names\">");
  var ipt_btn = document.createElement("<input type=\"button\" name=\"droplist_btn\" value=...>");
  var ipt_chk_read = document.createElement("<input type=\"checkbox\" name=\"read\">");
  var ipt_chk_write = document.createElement("<input type=\"checkbox\" name=\"write\">");
  var ipt_chk_required = document.createElement("<input type=\"checkbox\" name=\"required\">");
  var ipt_chk = document.createElement("<input type=\"checkbox\" name=\"taskchk\">");

  if(name) ipt_name.value = name;
  
  cell_name.appendChild(ipt_name);
  cell_name.appendChild(ipt_btn);
  cell_chk_read.appendChild(ipt_chk_read);
  cell_chk_write.appendChild(ipt_chk_write);
  cell_chk_required.appendChild(ipt_chk_required);
  cell_chk.appendChild(ipt_chk);

  ipt_chk_read.checked = isRead;
  ipt_chk_write.checked = isWrite;
  ipt_chk_required.checked = isRequired;
  
  //set event handler
  ipt_chk_write.relativeProp = ipt_chk_read;
  ipt_chk_write.onclick = function(){
      if(this.checked){ 
          this.relativeProp.checked = true;
          this.relativeProp.disabled = true;
      }else{
          this.relativeProp.disabled = false;
      }
  }
  if(isWrite) ipt_chk_read.disabled = true;
}	
//remove variables
function removeTaskVarible(){
   var objs=document.getElementsByName("taskchk");
   var index=0;
   for(i=0;i<objs.length;i++){
     if(objs[i].checked){
        index=objs[i].parentElement.parentElement.rowIndex;
        variablesTask.deleteRow(index);
        i--;
     }
   }
}
 function taskSend(){
       propertiesTaskNodeDialog.titleInput.value=document.all.Name.value;
       propertiesTaskNodeDialog.model.setTask(getTask());
       propertiesTaskNodeDialog.model.setText(propertiesTaskNodeDialog.titleInput.value);
	   propertiesTaskNodeDialog.titleInput.style.display = "none";
	   propertiesTaskNodeDialog.titleTxtCell.style.display = "";
	   propertiesTaskNodeDialog.titleInputCell.style.display = "none";
       propertiesTaskNodeDialog.model.setEditing(false);

       propertiesTaskNodeDialog.hide();
}

function decisionSend(){
	propertiesDecisionNodeDialog.titleInput.value = document.all.Name_.value;
 
	propertiesDecisionNodeDialog.model.setCondition(getCondition());
    
	propertiesDecisionNodeDialog.model.setText(propertiesDecisionNodeDialog.titleInput.value);
	propertiesDecisionNodeDialog.titleInput.style.display = "none";
	propertiesDecisionNodeDialog.titleTxtCell.style.display = "";
	propertiesDecisionNodeDialog.titleInputCell.style.display = "none";
    propertiesDecisionNodeDialog.model.setEditing(false);
	 
	propertiesDecisionNodeDialog.hide();
}

function forkSend(){
  propertiesForkNodeDialog.titleInput.value = document.all.forknode_name.value;
 
  propertiesForkNodeDialog.model.setText(propertiesForkNodeDialog.titleInput.value);
  propertiesForkNodeDialog.titleInput.style.display = "none";
  propertiesForkNodeDialog.titleTxtCell.style.display = "";
  propertiesForkNodeDialog.titleInputCell.style.display = "none";
  propertiesForkNodeDialog.model.setEditing(false);
   
  propertiesForkNodeDialog.hide();
}

function joinSend(){
  propertiesJoinNodeDialog.titleInput.value = document.all.joinnode_name.value;
 
  propertiesJoinNodeDialog.model.setText(propertiesJoinNodeDialog.titleInput.value);
  propertiesJoinNodeDialog.titleInput.style.display = "none";
  propertiesJoinNodeDialog.titleTxtCell.style.display = "";
  propertiesJoinNodeDialog.titleInputCell.style.display = "none";
  propertiesJoinNodeDialog.model.setEditing(false);
   
  propertiesJoinNodeDialog.hide();
}


function processSend(){
	if(!$("Beforesignal").value.match(/^\s*$/)){
	    processEventDialog.model.action.before_signal = $("Beforesignal").value;
	}
	if(!$("Aftersignal").value.match(/^\s*$/)){
	    processEventDialog.model.action.after_signal = $("Aftersignal").value;
	}
	if(!$("Nodeenter").value.match(/^\s*$/)){
	    processEventDialog.model.action.node_enter = $("Nodeenter").value;
	}
	if(!$("Nodeleave").value.match(/^\s*$/)){
	    processEventDialog.model.action.node_leave = $("Nodeleave").value;
	}
	if(!$("Processstart").value.match(/^\s*$/)){
	    processEventDialog.model.action.process_start = $("Processstart").value;
	}
	if(!$("Processend").value.match(/^\s*$/)){
	    processEventDialog.model.action.process_end = $("Processend").value;
	}
	if(!$("process_name").value.match(/^\s*$/)){
	   processEventDialog.model.setName($("process_name").value);
	}
	 
	processEventDialog.hide();
}

//remove all variables
function removeAllTaskVarible(){
   var objs=document.getElementsByName("taskchk");
   var index=0;
   for(i=0;i<objs.length;i++){
        index=objs[i].parentElement.parentElement.rowIndex;
        variablesTask.deleteRow(index);
        i--;
   }
}